'''
自定义返回处理
'''

# 导入控制返回的JSON格式的类
from rest_framework.renderers import JSONRenderer

class customrenderer(JSONRenderer):
    # 重构render方法
    def render(self, data, accepted_media_type=None, renderer_context=None):
        if renderer_context:
            if isinstance(data, dict):
                error_code = data.pop('error_code', 0)
                error_msg = data.pop('error_msg', 'success')
            else:
                error_msg = 'success'
                error_code = 0

            # 重新构建返回的JSON字典

            if isinstance(data, dict):
                for key in data:
                    # 判断是否有自定义的异常字段
                    if key == 'error_msg':
                        error_msg = data[key]
                        data = ''
                        error_code = data['error_code']

            status = 1
            if error_code > 0:
                status = 0

            ret = {
                'status': status,
                'error_code':  error_code,
                'error_msg': error_msg,
                'response_data': data,
            }

            # 返回JSON数据
            return super().render(ret, accepted_media_type, renderer_context)
        else:
            return super().render(data, accepted_media_type, renderer_context)